//
//  KWallDynamicsViewController.m
//  Keping
//
//  Created by apple on 2017/12/7.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KWallDynamicsViewController.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import "KWallDynamicsCell.h"
#import <TZImagePickerController/TZAssetModel.h>
#import <TZImagePickerController/TZImageManager.h>
#import "KUser.h"
#import "KUserData.h"
#import "KUploadImageRequest.h"
#import "KStatusRequest.h"

@interface KWallDynamicsViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, YYTextViewDelegate>

@property (nonatomic, weak) IBOutlet UIImageView *avatarView;
@property (nonatomic, weak) IBOutlet UILabel *nickeName;
@property (nonatomic, weak) IBOutlet YYTextView *textView;
@property (nonatomic, weak) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dynamicsImgs;

@end

@implementation KWallDynamicsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = kWhiteColor;
    [self.collectionView registerNib:[UINib nibWithNibName:[KWallDynamicsCell className] bundle:nil] forCellWithReuseIdentifier:[KWallDynamicsCell className]];
    KPartyView *user = [KPartyView unarchive];
    self.nickeName.text = user.nickName;
    [self.avatarView sd_setImageWithURL:[NSURL URLWithString:[KGetImageURL stringByAppendingString:user.profile]] placeholderImage:nil];
    self.textView.returnKeyType = UIReturnKeyDone;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Post" style:UIBarButtonItemStyleDone target:self action:@selector(pushDynamics)];
}

- (NSMutableArray *)dynamicsImgs {
    if (!_dynamicsImgs) {
        _dynamicsImgs = [NSMutableArray new];
    }
    return _dynamicsImgs;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.dynamicsImgs.count < 9) {
        return self.dynamicsImgs.count + 1;
    }
    return self.dynamicsImgs.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = (kScreenWidth - 10 * 2) / 3;
    CGSize size = CGSizeMake(width, 100);
    return size;
}

//定义每个Section的四边间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);//分别为上、左、下、右
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0.0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0.0;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger item = indexPath.item;
    KWallDynamicsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[KWallDynamicsCell className] forIndexPath:indexPath];
    if (item == 0) {
        cell.addImg = @"add-photo_icon";
    } else {
        cell.model = [self.dynamicsImgs objectAtIndex:item - 1];
    }
    WEAKSELF
    cell.deleteWallDynamiscsImg = ^(TZAssetModel *model) {
        [weakSelf.dynamicsImgs enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isEqual:model]) {
                [weakSelf.dynamicsImgs removeObjectAtIndex:idx];
                if (self.dynamicsImgs.count == 9) {
                    [weakSelf.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:idx inSection:0]]];
                } else {
                    [weakSelf.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:idx + 1 inSection:0]]];
                }
            }
        }];
    };
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger item = indexPath.item;
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if (item == 0 && self.dynamicsImgs.count < 9) {
        WEAKSELF
        TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:nil ];
        imagePickerVC.allowPickingVideo = NO;
        imagePickerVC.selectedAssets = self.dynamicsImgs;
        
        [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            [weakSelf.dynamicsImgs removeAllObjects];
            [weakSelf.dynamicsImgs addObjectsFromArray:assets];
            [weakSelf.collectionView reloadData];
        }];
        [weakSelf presentViewController:imagePickerVC animated:YES completion:nil];
    }
}

- (void)pushDynamics {
    [self showLoading];
    WEAKSELF
    __block NSMutableArray *imgsUrl = [NSMutableArray new];
    dispatch_group_t group = dispatch_group_create();
    for (int i = 0; i < self.dynamicsImgs.count; i++) {
        dispatch_group_enter(group);
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            TZAssetModel *model = [weakSelf.dynamicsImgs objectAtIndex:i];
            [[TZImageManager alloc] getOriginalPhotoWithAsset:model completion:^(UIImage *photo, NSDictionary *info) {
                KUploadImageRequest* imgRequest = [[KUploadImageRequest alloc] initWithUploadImage:photo compression:0.5];
                [imgRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
                    NSDictionary *dict = request.responseObject;
                    NSInteger statusCode = [[dict objectForKey:@"statusCode"] integerValue];
                    if (statusCode == 200) {
                        [imgsUrl addObject:[dict objectForKey:@"imageUrl"]];
                    }
                    dispatch_group_leave(group);
                } failure:^(__kindof KBaseRequest * _Nonnull request) {
                    dispatch_group_leave(group);
                }];
            }];
            
        });
    }
    
    dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *urls = @"";
        for (int i = 0; i < imgsUrl.count; i++) {
            if (i == 0)
                urls = [urls stringByAppendingString:[NSString stringWithFormat:@"%@",[imgsUrl objectAtIndex:i]]];
            else
                urls = [urls stringByAppendingString:[NSString stringWithFormat:@",%@",[imgsUrl objectAtIndex:i]]];
        }
        kDynamicsRequest *request = [[kDynamicsRequest alloc] init];
        request.params = @{@"imageUrls":urls,@"summary":self.textView.text,@"updateBy":[KAppConfig sharedConfig].communityId};
        [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf hideHUD];
            NSDictionary *dict = request.responseObject;
            NSInteger statusCode = [[dict objectForKey:@"statusCode"] integerValue];
            if (statusCode == 200) {
                KLog(@"%@",dict);
                [weakSelf showSuccess:[dict objectForKey:@"msg"]];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
        } failure:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf hideHUD];
            [weakSelf showError:request.error];
        }];
    });
}

- (BOOL)textView:(YYTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
